package jwt

import (
	"net/http"
	"hytx_media/pkg/e"
	"hytx_media/pkg/util"

	"github.com/gin-gonic/gin"
	"strings"
	"hytx_media/models"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		var data interface{}

		code = e.SUCCESS
		//token := c.Query("token")

		Authorization := c.GetHeader("Authorization")

		if Authorization == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": code,
				"msg":  e.GetMsg(code),
				"data": data,
			})

			c.Abort()
			return
		}

		sliceToken := strings.Split(Authorization, " ")
		token := sliceToken[1]
		var (
			claims *util.Claims
			err error
		)
		if token == "" {
			code = e.INVALID_PARAMS
		} else {
			claims, err = util.ParseToken(token)
			if err != nil {
				code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
			}
		}

		if code != e.SUCCESS {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": code,
				"msg":  e.GetMsg(code),
				"data": data,
			})

			c.Abort()
			return
		}
		//查询user
		user, err := models.GetUserById(claims.Sub)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": code,
				"msg":  e.GetMsg(code),
				"data": data,
			})

			c.Abort()
			return
		}
		c.Set("user", user)
		c.Next()
	}
}
